<?php

namespace app\index\controller;

use think\Controller; 
use app\common\library\Auth;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Hook;
use think\facade\Session;
use think\facade\Validate;
use think\facade\Lang;
use think\facade\Env;

/**
 * 会员中心
 */
class User extends Controller
{

    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third'];
    protected $noNeedRight = ['*'];

    public function initialize()
    {   
        parent::initialize();

        // 定义是否Dialog请求
        !defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? TRUE : FALSE);

        $this->auth = Auth::instance();
        $auth = $this->auth;        
        //移除HTML标签
        $this->request->filter('strip_tags');
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());
        $token = session('login_token');
        // dump($token);die;
        // 如果有使用模板布局
        // dump($this->layout);die;
        
        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        $this->view->assign('user', $this->auth->getUser());
        // dump($this->auth->getUser());die;
        // 语言检测
        $lang = strip_tags($this->request->langset());

        $site = Config::get("site.");

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            'modulename'     => $modulename,
            'controllername' => $controllername,
            'actionname'     => $actionname,
            'jsname'         => 'frontend/' . str_replace('.', '/', $controllername),
            'moduleurl'      => rtrim(url("/{$modulename}", '', false), '/'),
            'language'       => $lang
        ];
        $config = array_merge($config, Config::get("template.tpl_replace_string"));

        Config::set('upload', array_merge(Config::get('upload.'), $upload));       
        $menu_url = $config['modulename'].'/'.$config['controllername'].'/'.$config['actionname'];
        if ($this->layout) {
            if($menu_url !='index/user/login'){
                $this->view->engine->layout('layout/' . $this->layout);
            }
        }
        // 配置信息后
        Hook::listen("config_init", $config);
        // 加载当前控制器语言包
        $this->loadlang($controllername);
        $this->assign('site', $site);
        $this->assign('config', $config);
        $this->assign('menu_url', $menu_url);
        // dump($menu_url);die;
        // if($token == ''){
        //     $this->redirect("index/user/login"); //后修改
        // }
        $menu = '';
        if($token != ''){            
            $data_menu = array(
                "token" => $token,
                "terminal" => "web"
            );
            // dump($data_menu);die;
            $data_menu_string = json_encode($data_menu);
            // dump($data_menu_string);die;
            $curlopt_menu = array(
                CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_menu_string ) ),
                CURLOPT_TIMEOUT=>Config::get("site.api_timeout"),
            );
            $getmenu_url = request()->domain().'/api/user/menu';
            $menu_res = curl_post($getmenu_url,$data_menu_string,$curlopt_menu);
            // dump($menu_res);die;
            $menu_res = json_decode($menu_res,true);
            // dump($menu_res['data']);die;
            switch ($menu_res['code']) {
                case '1':
                    # code...
                    $menu = $menu_res['data'];
                    break;
                case '403':
                    Session::delete("login_token");
                    Session::delete("user_name");
                    $this->error($menu_res['msg']);
                    // $this->redirect($menu_res['msg']);
                    break;
                case '401':
                    Session::delete("login_token");
                    Session::delete("user_name");
                    $this->redirect("index/user/login");
                case '0':
                    $this->error($menu_res['msg']);
                    break;
                default:
                    # code...
                    break;
            }
                    
        }else{
            $menu = '';
        }
        // dump($menu);die;
        $this->assign('menu',$menu);
        $this->assign('user_name',session('user_name'));
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        Lang::load(Env::get('app_path') . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }    

    /**
     * 会员中心
     */
    public function index()
    {   
        $token = session('login_token');
        if($token == ''){
            $this->redirect("index/user/login"); //后修改
        }
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {   
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                // 'password'  => 'require|length:6,30',
                'password' => ['regex'=>'/^(?!.*[\s])(?=.*[\d])?(?=.*[a-zA-Z])(?=.*[\d]).{6,30}$/'],
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => '账户必须3-50位字符',
                'password.require' => 'Password can not be empty',
                // 'password.length'  => '密码必须6-30位字符， 至少包含数字和字母，不包含空格！',
                'password.regex'  => '密码必须6-30位字符，至少包含数字和字母，不包含空格！',
            ];
            $data = [
                'account'   => $account,    //用户名
                'password'  => $password,   //密码
                // '__token__' => $token,
                'terminal'  => 'web',       //终端
            ];

            $validate   = Validate::make($rule,$msg);
            // $validate = new Validate($rule, $msg);
            $result = $validate->check($data);

            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }

            ##  调接口登录
            $url = request()->domain().'/api/user/login';
            $data = [
                'account'   => $account,    //用户名
                'password'  => md5($password),   //密码
                // '__token__' => $token,
                'terminal'  => 'web',       //终端
            ];
            $data_string = json_encode($data);
            // dump($data_string);die;
            $curlopt = array(
                CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_string ) ),
                CURLOPT_TIMEOUT=>Config::get("site.api_timeout"),
            );
            // dump($curlopt);die;
            $res = curl_post($url,$data_string,$curlopt);
            $res = json_decode($res,true);           
            // dump($res);die;
            if($res['code'] == 1){  //根据接口返回的code判断是否登录成功
                //  获取菜单接口   跳转到第一个菜单的链接                                
                $data_menu = array(
                    "token" => $res['data']['token'],
                    "terminal" => "web"
                );
                $data_menu_string = json_encode($data_menu);
                $curlopt_menu = array(
                    CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_menu_string ) ),
                    CURLOPT_TIMEOUT=>Config::get("site.api_timeout"),
                );
                $getmenu_url = request()->domain().'/api/user/menu';
                $get_rule = request()->domain().'/api/user/rule';
                $user_info = request()->domain().'/api/user/info';
                $menu_res = curl_post($getmenu_url,$data_menu_string,$curlopt_menu);
                $menu_res = json_decode($menu_res,true);
                $rule_res = curl_post($get_rule,$data_menu_string,$curlopt_menu);
                $rule_res = json_decode($rule_res,true);
                $info = curl_post($user_info,$data_menu_string,$curlopt_menu);
                $info = json_decode($info,true);
                $expired= isset($info['data']['expired']) ? $info['data']['expired'] : 0; //过期时间
                $expireds = strtotime($expired);
                $now_time = time();
                $ip = isset($info['data']['ip']) ? $info['data']['ip'] : '';    //客户Ip
                session("ip",$ip);
                if($expireds < $now_time){
                    $this->error('到期时间:'.$expired.'请联系管理员');
                }
                if($menu_res['code'] == 1 && is_array($menu_res['data']) && count($menu_res['data']) == 0){
                    $this->error('没有菜单权限');
                }else if($menu_res['code'] != 1){
                    $this->error($menu_res['msg']);
                }else{                    
                    $url = reset($menu_res['data'])['name'];
                    session("user_rule",$rule_res);
                    session("user_power",$menu_res['data']);
                    session("login_token",$res['data']['token']);
                    session("user_name",$res['data']['nickname']);
                    $this->success(__('Logged in successful'),url($url));
                }
                // $this->redirect($url);       
                // $this->redirect($url,['token' => $res['data']['token']]);           
            }else{
                $this->error($res['msg']);
            }            
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        // var_dump($referer);exit;
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $url = request()->domain().'/api/user/logout';
        $data = array(
           'token' => session('login_token'),
           'terminal' => 'web'
        );
        $data_string = json_encode($data);
        $curlopt = array(
            CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_string ) ),
            CURLOPT_TIMEOUT=>Config::get("site.api_timeout"),
        );
        // dump($curlopt);die;
        $res = curl_post($url,$data_string,$curlopt);
        $res = json_decode($res,true);    
        if($res['code'] == 1){
            // session(null);
            Session::delete("user_rule");
            Session::delete("user_power");
            Session::delete("login_token");
            Session::delete("user_name");
            Session::delete("ip");
            $this->redirect("index/user/login");
        }

        if($res['code'] == 401){
            Session::delete("user_rule");
            Session::delete("user_power");
            Session::delete("login_token");
            Session::delete("user_name");
            Session::delete("ip");
            $this->redirect("index/user/login");
        }

        if($res['code'] == 403){            
            $this->error($res['msg']);
        }
        
        // $this->auth->logout();
        // $this->success(__('Logout successful'), url('user/login'));
    }

    /**
     * 基本信息
     */
    public function info()
    {
        $token = session('login_token');
        //需要修改这里
        if($token == ''){
            $this->redirect("index/user/login"); 
        }
        // dump($token);die;
        //调接口获取信息
        $url = request()->domain().'/api/user/info';
        $data = array(
            'token' => $token,
            'terminal' => 'web'
        );
        $data_string = json_encode($data);
        $curlopt = array(
            CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_string ) ),
            CURLOPT_TIMEOUT=>Config::get("site.api_timeout"),
        );
        // dump($curlopt);die;
        $res = curl_post($url,$data_string,$curlopt);
        $res = json_decode($res,true);
        //dump($res);die;
        $this->view->assign('title', __('基本信息'));
        switch ($res['code']) {
            case '1':
                # code...
                $this->view->assign('code',$res['code']);
                $this->view->assign('msg',$res['msg']);
                $this->view->assign('info',$res['data']);
                return $this->view->fetch();
                break;
            case '401':
                session(null);
                $this->redirect("index/user/login");
                break;
            case '0':
                $this->view->assign('code',$res['code']);
                $this->view->assign('msg',$res['msg']);
                $this->view->assign('info',$res['data']);
                // echo json_encode($res,JSON_UNESCAPED_UNICODE);
                return $this->view->fetch();
                break;
             case '403':
                $this->view->assign('code',$res['code']);
                $this->view->assign('msg',$res['msg']);
                $this->view->assign('info',$res['data']);
                // echo json_encode($res,JSON_UNESCAPED_UNICODE);
                return $this->view->fetch();
                break;
            default:
                # code...
                break;
        }        
    }

}
